package com.hao.proxy.http;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.Map;

import org.jsoup.Connection.Method;

import com.hao.proxy.model.Proxy;


public class UrlHttpExecuter implements HttpExecuter {
	
	@Override
	public HttpResponse execute(HttpRequest request) throws IOException {
		return execute(request, null);
	}
	
	@Override
	public HttpResponse execute(HttpRequest request, Proxy proxy) throws IOException {
		HttpURLConnection connection;
		if(proxy != null){
			java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()));
			connection = (HttpURLConnection) new URL(request.getUrl()).openConnection(p);
		}else{
			connection = (HttpURLConnection) new URL(request.getUrl()).openConnection();
		}
		//添加请求头
		Map<String, String> headers = request.getHeaderMap();
        if (headers != null) {
            for (String key : headers.keySet()) {
                connection.setRequestProperty(key, headers.get(key));
            }
        }
        //设置读去超时时间为10秒
        connection.setReadTimeout(request.getReadTimeout());
        //设置链接超时为10秒
        connection.setConnectTimeout(request.getConnectTimeout());
        //设置请求方式,GET,POST
        connection.setRequestMethod(request.getMethod().toString());
        //接受输入流
        connection.setDoInput(true);
        //写入参数
        StringBuilder builder = new StringBuilder();
        if(request.getMethod() != Method.GET){
        	Map<String, String> postMap = request.getPostMap();
        	if(postMap.size() > 0){
        		//写入参数 用&分割。
        		for (Object key : postMap.keySet()) {
                    builder.append(key + "=" + postMap.get(key) + "&");
                }
        	}else if(request.getPostBody() != null){
        		builder.append(request.getPostBody());
        	}
        	//启动输出流，当需要传递参数时需要开启
        	connection.setDoOutput(true);
        	OutputStream output = connection.getOutputStream();
        	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, request.getCharset()));
        	writer.write(builder.toString());
        	writer.flush();
        	writer.close();
        }
        
        //发起请求
        connection.connect();
        HttpResponse resopnse = new HttpResponse(connection.getResponseCode(), connection.getResponseMessage(), connection.getRequestProperties(), getResponseData(connection.getInputStream()));
		return resopnse;
	}
	
	
	public byte[] getResponseData(InputStream inputStream) throws IOException{
		ByteArrayOutputStream baos = null;
		try{
			baos = new ByteArrayOutputStream();
			int len = 1024;
			byte tmp [] = new byte[len];
			int i ;
			while((i=inputStream.read(tmp, 0, len))>0){
				baos.write(tmp, 0, i);
			}
			return baos.toByteArray();
		}finally{
			if(baos != null){
				baos.close();
			}
		}
	}
	
	public String getBody(HttpURLConnection connection, String... charsets) {
        String charset = "UTF-8";
        if (charsets.length > 0) {
            charset = charsets[0];
        }
        try {
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset));
            String line = bufferedReader.readLine();
            StringBuilder builder = new StringBuilder();
            while (line != null) {
                builder.append(line);
                line = bufferedReader.readLine();
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
